package com.duke.shaking.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class PhotoUtils {
	private static final String TAG = "PhotoUtils";
	public static Context context;
	
	public static String AVATAR_DIR_NAME = "avatar";
	public static String AVATAR_FILE_NAME = "avatar";
	public static String AVATAR_FILE_EXT_NAME=".jpg";
	public static String PHOTO_FILE_NAME = "photo";
	
	public static void init(Context context) {
		PhotoUtils.context = context;
	}
	
	public static File saveAvatar(Bitmap bitmap, String mobile) {
		File dir = getAvatarDir();
		File file = new File(dir, AVATAR_FILE_NAME + "-" + mobile + AVATAR_FILE_EXT_NAME);
		try {
			FileOutputStream fos = new FileOutputStream(file); 
			bitmap.compress(CompressFormat.JPEG, 100, fos); 
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			file = null;
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			file = null;
			e.printStackTrace();
		} 
		//return file.getAbsolutePath();
		return file;
	}
	
	public static Bitmap loadImage(Uri uri) {
		ContentResolver resolver = context.getContentResolver();
		//photo = BitmapFactory.decodeFile(uri.getPath());
		try {
			return MediaStore.Images.Media.getBitmap(resolver, uri);
			
		} catch (FileNotFoundException e) {
		} catch (IOException e) {
		}
		return null;
	}
	
	public static String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

	private static Bitmap imageZoom(Bitmap bitMap, int size) {
		//图片允许最大空间   单位：KB
		double maxSize =100.00;
		//将字节换成KB
		double mid = size/1024;
		//判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			//获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			//开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
		}
		return bitMap;
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

	public static String savePhotoForUpload(Uri uri, String mobile) {
		String filePath = getRealPathFromURI(uri);
		int size = getPhotoSize(filePath);
		
		Bitmap bitmap = loadImage(uri);
		Bitmap smallBitmap = imageZoom(bitmap, size);
		File file = saveAvatar(smallBitmap, mobile);
		return file.getAbsolutePath();
	}
	
	private static int getPhotoSize(String filePath) {
		File file = new File(filePath);
		int size = 0;
		if (file.exists()) {
            try {
				FileInputStream fis = new FileInputStream(file);
				size = fis.available();
				Log.i(TAG, "image size =" + size);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		return size;
	}

	public static File getAvatarDir() {
		File appDir = context.getFilesDir();
		File dir = new File(appDir, AVATAR_DIR_NAME);
		if(!dir.exists()) {
			dir.mkdir();
		}
		return dir;
	}
}
